package com.wdf.project03.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wdf.project03.pojo.Result;
import com.wdf.project03.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,Object handler) throws Exception{
        //1、获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url:{}",url);
        if(url.contains("login")){
            log.info("登录操作，放行...");
            return true;
        }
        String jwt = req.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空，返回未登录的信息");
            Result error = Result.error("NOT_LGOIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析令牌失败, 返回未登录错误信息");
            Result error = Result.error("NOT_LGOIN");
            String notLogin = JSONObject.toJSONString(error);
            return false;
        }
        log.info("令牌合法,放行");
        return true;
    }
}
